package com.juku2024.juku

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.rabbit.videoplayer.OnChangeEpisodeListener
import com.rabbit.videoplayer.listener.OnVodCompleteListener
import com.rabbit.videoplayer.listener.OnVodErrorListener
import com.rabbit.videoplayer.listener.player.OnPreparedListener
import com.rabbit.videoplayer.response.PlayerType
import com.rabbit.videoplayer.response.VideoPlayModel
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.tools.*
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.utils.CommonAdTools
import com.juku2024.juku.model.EpisodesResponse
import com.juku2024.juku.model.WatchEvent
import com.juku2024.juku.viewmodel.DownloadViewModel
import com.juku2024.juku.widget.ControlEpisodeListView
import com.rabbit.videoplayer.MixPlayerView
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DatabaseUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.model.DownloadType
import org.greenrobot.eventbus.EventBus
import java.io.File

class DownloadPlayerActivity : BaseActivity() {

    private var currentPos = 0
    private var startPosition = 0L
    @PlayerType
    private var playerType: Int = PlayerType.ALIYUN
    private var title: String? = null
    private var downloadUrl: String? = null
    // 下载广告
    private var downloadPlayerAdTools: CommonAdTools? = null
    // 当前已下载的视频任务合集
    private val finishDlList by lazy { ArrayList<DownloadEntity>() }
    private val episodeList by lazy { ArrayList<EpisodesResponse>() }
    private val viewModel by lazy { getViewModel(DownloadViewModel::class.java) }

    private lateinit var videoPlayer: MixPlayerView
    private lateinit var fullEpisodeView: ControlEpisodeListView

    override fun beforeOnCreate() {
        hideBottomBar()
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_download_player
    }

    @Suppress("DEPRECATION")
    override fun initView() {
        videoPlayer = findViewById(R.id.videoPlayer)
        fullEpisodeView = findViewById(R.id.fullEpisodeView)


        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            val controller = ViewCompat.getWindowInsetsController(videoPlayer)
            if (controller == null) {
                window.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
                )
            } else {
                controller.hide(WindowInsetsCompat.Type.statusBars())
                controller.hide(WindowInsetsCompat.Type.navigationBars())
            }
        } else {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
        }

        // 隐藏底部按钮
        videoPlayer.setVideoModel(VideoPlayModel.FULL_SCREEN)
    }

    override fun bindEvent() {
        fullEpisodeView.setEpisodeClickCallback(object : com.rabbit.videoplayer.listener.OnEpisodeClickCallback {
            override fun onEpisodeClick(position: Int, realPos: Int) {

                update()

                // 设置是否显示播放下一个
                performPlay(position)
            }
        })

        videoPlayer.setVodPreparedListener(object: OnPreparedListener {
            override fun onPrepared() {
                videoPlayer.start()
            }
        })

        // 播放器切换剧集监听
        videoPlayer.setVodChangeEpisodeListener(object : OnChangeEpisodeListener {
            override fun onChangeEpisode(position: Int) {
                // 获取当前正在播放的剧集的position
                update()

                performPlay(position)
            }

            override fun onPlayNext(): Boolean {
                // 当前正在播放的位置
                val currentPlayingItemIndex = episodeList.indexOfFirst { it.isPlaying }
                // 已经最后一集了，不再播放下一集
                if (currentPlayingItemIndex >= episodeList.size - 1) return false

                update()

                // 当前要播放的位置
                val targetIndex = currentPlayingItemIndex + 1
                // 播放视频
                performPlay(targetIndex)
                return targetIndex < episodeList.size - 1
            }

            override fun showEpisodeList() {
                fullEpisodeView.onEpisodeSelected()
            }

            override fun onPause() {
                update()
            }
        })

        videoPlayer.setVodCompleteListener(object : OnVodCompleteListener {
            override fun onVodComplete(): Boolean {
                // 默认是继续播放下一集
                val currentSource = episodeList.size
                val index = episodeList.indexOfFirst { it.isPlaying }
                if (index >= currentSource - 1) { // 播放到最后一集，无法再自动播放了
                    return true
                }
                return false
            }
        })

        // 播放器出错提示
        videoPlayer.setVodErrorListener(object : OnVodErrorListener {

            override fun onRetry() {
                if (TextUtils.isEmpty(downloadUrl)) return
                videoPlayer.showLoadingStatus()
                // 重置广告标签
                videoPlayer.postDelayed({
                    videoPlayer.playVideo(
                        // 播放url
                        url = downloadUrl!!,
                        title,
                        // 跳转进度
                        startPosition = startPosition,
                        currentPos,
                        finishDlList.size,
                        isPlayDownloadVideo = true,
                        playerType = playerType
                    )
                }, 500)
            }

            override fun onVodError(errorMsg: String?): Boolean {
                startPosition = videoPlayer.getCurrentPosition() + 5000
                LogC.e("播放器SDK -> 播放失败：$errorMsg")
                return true
            }
        })
    }


    override fun init(savedInstanceState: Bundle?) {
        val videoId = intent?.getLongExtra(Constants.AROUTER_KEY_VIDEO_ID, 0L)?:0L
        if (videoId <= 0) {
            // 播放信息错误
            showErrorDialog("下载文件出错，无法正常播放！","返回", { finish() })
            return
        }
        // 当前播放的列表
        val episodeIndex = intent?.getIntExtra(Constants.AROUTER_KEY_DOWNLOAD_INDEX, 0)?:0

        viewModel.getDownloadFinishEpisodeList(videoId, { downloadList ->
            if (isActivityNotActive()) return@getDownloadFinishEpisodeList
            if (downloadList.isEmpty()) {
                // 播放信息错误
                showErrorDialog("下载文件出错，无法正常播放！","返回", { finish() })
                return@getDownloadFinishEpisodeList
            }
            finishDlList.addAll(downloadList)
            var currentPosition = 0
            // 获取所有视频名称
            finishDlList.forEachIndexed { index, downloadEntity ->
                val episode = EpisodesResponse()
                episode.isPlaying = downloadEntity.episode == episodeIndex
                episode.title = downloadEntity.episodeName
                episode.isDownloaded = false
                episode.isPlayed = false
                episode.isLockVideoAd = false
                episode.category = downloadEntity.category
                episodeList.add(episode)
                if (episode.isPlaying) {
                    currentPosition = index
                }
            }
            // 播放
            performPlay(currentPosition)
        }, {
            if (isActivityNotActive()) return@getDownloadFinishEpisodeList
            // 播放信息错误
            showErrorDialog("下载文件出错，无法正常播放！","返回", { finish() })
        })
    }


    private fun performPlay(index: Int) {
        currentPos = index
        val downloadEntity = finishDlList.getOrNull(index)
        if (downloadEntity == null) {
            // 播放信息错误
            showErrorDialog("下载文件出错，无法正常播放！","返回", { finish() })
            return
        }
        downloadUrl = downloadEntity.playPath

        LogC.e("下载播放地址 -> $downloadUrl")

        if (TextUtils.isEmpty(downloadUrl)) {
            // 播放信息错误
            showErrorDialog("下载文件出错，无法正常播放！","返回", { finish() })
            return
        }

        title = if (downloadEntity.category == Constants.VIDEO_CATEGORY_ALBUM) {
            String.format("%s  第%s集", downloadEntity.videoName, downloadEntity.episodeName)
        } else if (downloadEntity.category == Constants.VIDEO_CATEGORY_VARIFY){
            if (downloadEntity.episodeName?.endsWith("期") == true) {
                String.format("%s  %s", downloadEntity.videoName, downloadEntity.episodeName)
            } else {
                String.format("%s  %s期", downloadEntity.videoName, downloadEntity.episodeName)
            }
        } else {
            String.format("%s  %s", downloadEntity.videoName, downloadEntity.episodeName)
        }
        startPosition = downloadEntity.watchTime

        val playerType: Int
        val isHideOtherPlayers: Boolean
        if (downloadEntity.downloadType == DownloadType.DEFAULT) {
            playerType = -1
            isHideOtherPlayers = false
        } else {
            playerType = PlayerType.TX
            isHideOtherPlayers = true
        }
        // 重置广告标签
        videoPlayer.playVideo(
            // 播放url
            url = downloadUrl!!,
            title = title,
            // 跳转进度
            startPosition = startPosition,
            currentPlayIndex = currentPos,
            episodeSize = finishDlList.size,
            isPlayDownloadVideo = true,
            headerMap = null,
            playerType = playerType,
            isHideOtherPlayers = isHideOtherPlayers
        )


        episodeList.forEachIndexed { position, episodesResponse ->
            episodesResponse.isPlaying = position == index
        }
        fullEpisodeView.onVodInit(episodeList)

        loadInterstitialAd()
    }


    // 更新观看进度
    private fun update() {
        val episode = finishDlList.getOrNull(currentPos)?:return
        try {
            val currentPosition = videoPlayer.getCurrentPosition()
            if (currentPosition < 2000) return

            val duration = videoPlayer.getDuration()
            episode.watchTime = if (duration - currentPosition < 10 * 1000) {
                duration - 10 * 1000
            } else {
                currentPosition
            }

            DatabaseUtils.insertTask(episode)
            EventBus.getDefault().post(WatchEvent(episode.url, episode.watchTime))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        videoPlayer.onVodResume()
    }

    override fun onPause() {
        super.onPause()
        videoPlayer.onVodSuspend()
        update()
    }
    override fun onDestroy() {
        super.onDestroy()
        videoPlayer.release()
        downloadPlayerAdTools?.release()
    }

    @Suppress("DEPRECATION")
    private fun hideBottomBar() {
        try {
            //for new api versions.
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun loadInterstitialAd() {
        downloadPlayerAdTools?.release()
        downloadPlayerAdTools = CommonAdTools()
        downloadPlayerAdTools?.loadAd(this, AdConstants.AD_ID_DOWNLOAD_PLAYER_INTERSTITIAL_AD, object: OnLoadAdCallback(){
            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                if (isActivityNotActive()) return
                downloadPlayerAdTools?.showAdInActivity(this@DownloadPlayerActivity)
            }

            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                LogC.d("InterstitialAd -> showAd 插屏广告关闭 errorCode=$errorCode")
                if (isActivityNotActive()) return
                videoPlayer.start()

            }

            override fun onAdComplete() {
                super.onAdComplete()
                if (isActivityNotActive()) return
                // 如果有视频前插广告，且已经加载完成，就播放视频
                videoPlayer.start()
            }
        })
    }
}

